package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.codehaus.jackson.map.ObjectMapper;

import utils.CommentsHelper;
import entities.Comment;

/**
 * Servlet implementation class CommentsServlet
 */
@WebServlet("/Comments")
public class CommentsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String COMMENTS = "comments";
	private static final String TEXT = "commentText";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CommentsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json");
		response.setStatus(200);
		List<Comment> itemsList = CommentsHelper.getComments(
				ServletsUtil.castRequestParameter(ItemsServlet.ITEM_ID, request, response)
				,ServletsUtil.getStartFrom(request, response), 
				ServletsUtil.getPageNumber(request, response)
				);
		
			ObjectMapper mapper = new ObjectMapper();
			PrintWriter writer = response.getWriter();
			writer.write(
						"{\"" + COMMENTS +"\":" + mapper.writeValueAsString(itemsList) + "}"					
						);
			writer.flush();
	}
	

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Comment comment = getComment(request);
		boolean result = CommentsHelper.postComment(comment);
		response.setContentType("text/json");
		try {
			response.getWriter().write(
					new JSONObject().put(ServletsUtil.RESULT, result).toString()
					);
		} catch (JSONException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}
	


	private static Comment getComment(HttpServletRequest request) {
		Comment comment = new Comment(); 
		JSONObject jsonObject ;
		String str = null;
		
		try {
			str = request.getReader().readLine();
			jsonObject = new JSONObject(str);
					comment.setItemID(jsonObject.optLong(ItemsServlet.ITEM_ID));
					comment.setUserID(ServletsUtil.getUserID(request));
					comment.setText(jsonObject.optString(TEXT));
			return comment;
		}catch (JSONException | IOException e){
			e.printStackTrace();
		}
		return null;
	}

}
